import prettytable
from color import *


def cut(obj, sec):
    return [obj[i : i + sec] for i in range(0, len(obj), sec)]


def formatWorldMap(
    world_map: dict, ifAxis: bool = True, pos: list[int] = None
) -> prettytable.PrettyTable:
    '''
    格式化地图
    '''
    if pos is None:
        pos = [0, 0]
    x_size = list(
        list(world_map.values())[0].keys()
    )  # 横宽（world_map为{y1:{x1:place,x2:place}}）
    y_size = list(world_map.keys())  # 竖高[y1,y2,y3,...]
    worldMap_talbe = prettytable.PrettyTable()  # 创建prettytable
    worldMap_talbe.vertical_char = " "  # 设置竖直线段为空
    worldMap_talbe.junction_char = "-"  # 设置连接符为=
    worldMap_talbe.horizontal_char = "-"

    if not ifAxis:  # 若ifAxis为False（是否输出坐标轴）
        worldMap_talbe.header = False
        table_header = [str(i) for i in x_size]
        worldMap_talbe.field_names = table_header
        for i in y_size:  # 重复行数次
            world_map_row = list(world_map[i].values())
            Place = world_map_row[pos[0]]
            if i == pos[1]:  # pos[x,y]，若纵坐标等于所处位置
                world_map_row[pos[0]] = f"{YELLOW}{Place}{NORMAL}"  # 将这一行的x坐标处标黄
            worldMap_talbe.add_row(world_map_row)  # 添加到table中

    else:  # 打印坐标轴（即在左侧添加一列数字，插入到world_map中）
        worldMap_talbe.header = True
        table_header = ["坐标|"]  # 表头新增一列供坐标显示
        table_header.extend(str(i) for i in x_size)
        worldMap_talbe.field_names = table_header
        for i in y_size:
            world_map_row = world_map[i]
            # print(world_map_row)
            Place = world_map_row[pos[0]]
            if i == pos[1]:
                world_map_row[pos[0]] = f"{YELLOW}{Place}{NORMAL}"
                # print(world_map_row)
            index = ["{i}  |".format(i=i)]
            worldMap_talbe.add_row(index + list(world_map_row.values()))

    return worldMap_talbe.__str__().replace("  ", "　")


def formatPlaceInfo(
    name: str, info: str, if_exit: dict[bool], exit_objects: dict[str], units: dict[str]
) -> str:
    '''
    格式化位置信息
    '''
    info = info.replace("  ", "　")  # 将英文空格替换为全角空格，方便对齐
    string = f"{BLUE}{name}{NORMAL}" + "\n\n"
    string += info + "\n\n此地的去向有："
    for direction, value in if_exit.items():
        if value:
            string += "{Direction}: {Place}, ".format(
                Direction=direction, Place=exit_objects[direction]
            )
    if units:
        string += "\n\n这里有："
        for unit, amount in units.items():
            if amount == 1:
                string += f"{unit}, "
            else:
                string += f"{unit}x{amount}, "
    else:
        string += "\n\n这里空荡荡的，什么也没有。"
    return string


def formatUnitInfo(name: str, info: str, actions: list[str], amount: int):
    info = info.replace("  ", "　")  # 将英文空格替换为全角空格，方便对齐
    string = f"{BLUE}{name}{NORMAL}x{amount}\n{info}\n{BLUE}可进行的操作：{NORMAL}\n"
    for action in actions:
        string += f"　　-  {action}\n"

    return string
